<!-- 管理员 -->
<template>
  <div>
    <div>
      <!-- 搜索部分 -->
      <el-input
        clearable
        v-model.trim="configReq.username"
        @keyup.enter="getInfo"
        style="width: 250px; margin-right: 13px"
        placeholder="请输入管理员名称"
      />
      <el-button type="primary" :icon="Search" @click="debounce(getInfo)"
        >查找</el-button
      >
      <el-button
        type="primary"
        :icon="Edit"
        @click="
          () => {
            resetConfig();
            titleUpAdd = '创建';
            dialogUpAdd = true;
          }
        "
        v-btn="'sys:admin:create'"
        >添加</el-button
      >
    </div>
    <div style="margin-top: 20px">
      <!-- 表格 -->
      <el-table :data="infoList" border>
        <el-table-column prop="id" label="管理员ID" width="100" />
        <el-table-column prop="username" label="管理员名称" width="180" />
        <el-table-column prop="realname" label="真实姓名" />
        <el-table-column prop="phone" label="电话" />
        <el-table-column label="管理员角色">
          <template #default="scope">
            <el-tag
              v-for="item in scope.row.roleIds"
              :key="item"
              style="margin: 5px"
              >{{ roleOptions.find((v) => v.value == item)?.label }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              type="primary"
              @click="
                () => {
                  resetConfig();
                  titleUpAdd = '编辑';
                  Object.assign(dataUpAdd.adminDTO, scope.row);
                  dialogUpAdd = true;
                }
              "
              v-btn="'sys:admin:edit'"
              >修改</el-button
            >
            <el-button
              type="danger"
              @click="deleAdmin(scope.row.id)"
              v-btn="'sys:admin:delete'"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div>
      <!-- 添加和修改的弹出框 -->
      <el-dialog
        v-model="dialogUpAdd"
        :title="titleUpAdd"
        width="35%"
        destroy-on-close
      >
        <el-form
          ref="formRef"
          :model="dataUpAdd.adminDTO"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="用户名" prop="username">
            <el-input
              :disabled="titleUpAdd == '编辑'"
              v-model.trim="dataUpAdd.adminDTO.username"
              type="text"
            />
          </el-form-item>
          <el-form-item
            label="密码"
            prop="password"
            v-if="'编辑' != titleUpAdd"
          >
            <el-input v-model.trim="dataUpAdd.adminDTO.password" type="text" />
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input
              v-model.trim="dataUpAdd.adminDTO.phone"
              type="text"
              maxlength="11"
            />
          </el-form-item>
          <el-form-item label="真实姓名" prop="realname">
            <el-input v-model.trim="dataUpAdd.adminDTO.realname" type="text" />
          </el-form-item>
          <el-form-item
            label="角色"
            prop="roleIds"
            :rules="
              '编辑' != titleUpAdd
                ? [{ required: false }]
                : [
                    {
                      message: '角色不能为空',
                      trigger: 'change',
                      required: true,
                    },
                  ]
            "
          >
            <!-- v-model绑定对应value值 -->
            <el-select
              v-model="dataUpAdd.adminDTO.roleIds"
              multiple
              filterable
              placeholder="请选择角色"
            >
              <el-option
                v-for="item in roleOptions"
                :key="item?.value"
                :label="item?.label"
                :value="item?.value"
              />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button type="primary" @click="submitForm('formRef')">{{
              titleUpAdd == "编辑" ? "修改" : "新增"
            }}</el-button>
            <el-button @click="resetForm('formRef')">重置</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
    <div style="margin: 20px 0px">
      <!-- 分页组件 -->
      <paging v-bind="pageInfo" @changeReq="changeConfig"></paging>
    </div>
  </div>
</template>

<script>
import { post } from "@/utils/http";
import Paging from "@/components/paging/Paging";
import { Search, Edit } from "@element-plus/icons-vue";
export default {
  setup() {
    return {
      Search,
      Edit, //属性不用注册
    };
  },
  components: { Paging },
  data() {
    //密码验证
    let validatePass = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请输入密码"));
      } else {
        if (value.length < 6) {
          callback(new Error("密码长度不能为小于6"));
        }
        callback();
      }
    };
    //用户名验证
    let validateUser = (rule, value, callback) => {
      if (!value) {
        callback(new Error("用户名不能为空"));
      } else {
        callback();
      }
    };
    //手机号验证
    let validatePho = (rule, value, callback) => {
      if (!value) {
        callback(new Error("手机号不能为空"));
      } else {
        var reg = /^[1]([3-9])[0-9]{9}$/;
        if (!reg.test(value)) {
          callback(new Error("手机号格式错误"));
        }
        callback();
      }
    };
    //真实姓名验证
    let validateReal = (rule, value, callback) => {
      if (!value) {
        callback(new Error("真实姓名不能为空"));
      } else {
        var reg = /^[\u4e00-\u9fa5]+?$/;
        if (!reg.test(value)) {
          callback(new Error("真实姓名必须为中文"));
        }
        callback();
      }
    };
    return {
      id: 0, //点击行的管理员id
      infoList: [], //管理员列表
      roleOptions: [], //选择框角色列表
      titleUpAdd: "", //添加和修改弹出框的标题
      // 请求表格数据的配置
      configReq: {
        _gp: "admin",
        _mt: "list",
        username: "", //管理员名称
        page: 1,
        limit: 20,
      },
      // 传给分页组件的数据
      pageInfo: {
        page: 1, //跳转页数
        limit: 20, //显示条数
        total: 0,
      },
      //添加和修改管理员的数据
      dataUpAdd: {
        _gp: "admin",
        _mt: "",
        adminDTO: {
          username: "",
          password: "",
          phone: "",
          realname: "",
          roleIds: [],
        },
      },
      dialogUpAdd: false, // 显示添加和修改的弹出框
      rules: {
        username: [
          { validator: validateUser, trigger: "blur", required: true },
        ],
        password: [
          { validator: validatePass, trigger: "blur", required: true },
        ],
        phone: [{ validator: validatePho, trigger: "blur", required: true }],
        realname: [
          { validator: validateReal, trigger: "blur", required: true },
        ],
      },
    };
  },
  methods: {
    // 获取管理员数据的方法
    getInfo() {
      post(this.configReq)
        .then((res) => {
          if (200 == res.errno) {
            //成功状态码
            // console.log(res);
            this.infoList = res.data.items; //获取表格信息
            this.pageInfo.total = res.data.total; //获取总条数
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 组件触发的数据改变
    changeConfig(data) {
      Object.assign(this.configReq, data);
      this.getInfo();
    },
    // 获取角色信息的方法
    getRole() {
      post({
        _gp: "admin.role",
        _mt: "options",
      })
        .then((res) => {
          if (200 == res.errno) {
            //成功状态码
            this.roleOptions = res.data;
            // console.log( res.data)
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 删除管理员(点击确认)
    deleAdmin(id) {
      ElMessageBox.confirm("是否删除该管理员?", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        post({
          _gp: "admin",
          _mt: "delete",
          id: id, //目标删除Id
        })
          .then((res) => {
            if (200 == res.errno) {
              //成功状态码
              this.dialogDele = false; //关闭弹窗
              ElMessage.success("删除成功");
              this.getRole();
              this.getInfo(); //刷新数据
            }
          })
          .catch((err) => {
            console.log(err);
          });
      });
    },
    // 提交表单(添加修改管理员)
    submitForm(formEl) {
      this.$refs[formEl].validate((valid) => {
        //验证对应表单是否通过
        if (valid) {
          switch (this.titleUpAdd) {
            case "创建":
              this.dataUpAdd._mt = "create";
              this.updataAdd();
              break;
            case "编辑":
              delete this.dataUpAdd.adminDTO.password; //删除属性之后不提交密码
              this.dataUpAdd._mt = "edit";
              this.updataAdd();
              break;
          }
        }
      });
    },
    // 添加和修改共用的请求
    updataAdd() {
      this.dataUpAdd.adminDTO = JSON.stringify(this.dataUpAdd.adminDTO);
      post(this.dataUpAdd)
        .then((res) => {
          if (200 == res.errno) {
            //成功状态码
            this.dialogUpAdd = false; //关闭弹窗
            ElMessage.success(this.titleUpAdd + "成功"); //提示信息
            this.getInfo(); //刷新数据
          }
        })
        .catch((err) => {
          this.dialogUpAdd = false; //关闭弹窗
          console.log(err);
          return;
        });
    },
    // 重置管理员添加和修改的配置
    resetConfig() {
      this.dataUpAdd = {
        _gp: "admin",
        _mt: "",
        adminDTO: {
          username: "",
          password: "",
          phone: "",
          realname: "",
          roleIds: [],
        },
      };
    },
    // 重置表单
    resetForm(ref) {
      this.$refs[ref].resetFields();
    },
  },
  created() {
    this.getRole(); //获取角色数据
    this.getInfo(); //获取表格数据
  },
};
</script>

<style></style>
